package hp.com.servlet.AddressServlet;


import hp.com.entity.Address;
import hp.com.entity.Users;
import hp.com.service.AddressService;
import hp.com.service.impl.AddressServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/Address")
public class AddressServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        //判断是否登录且获取对象
        if(session.getAttribute("userSession")==null){
            resp.sendRedirect(req.getContextPath()+"/jbs/Login.jsp");
        }else{
            Users user = (Users)session.getAttribute("userSession");
            AddressService as = new AddressServiceImpl();
            List<Address> list=new ArrayList<>();
            //获取用户已经设置的地址信息
            try {
                list = as.getAddressById(user.getId());
            } catch (Exception e) {
                e.printStackTrace();
            }
            req.setAttribute("addressList",list);
            req.setAttribute("userSession",user);
            req.getRequestDispatcher(req.getContextPath()+"/jbs/address.jsp").forward(req,resp);
        }
    }
}
